// pages/cardGet/index.js
const ImageSource = require("../../utils/image_path.js");
const { request }  = require('../../request/index.js');
const crypto = require("../../utils/test");
const wordRandom = require("../../utils/nameRandom.js")
const dataGet=require("../../request/dataGet.js")

const app=getApp();
Page({
    data: {
        NavbarHeight:app.globalData.navBarHeight + app.globalData.statusBarHeight,
        WindowWidth:app.globalData.windowWidth,
        ScreenHeight:app.globalData.ScreenHeight,
        nowTime:app.globalData.nowTime,
        navigationSetting:{
            title:'抽卡空间',
            model:0,
        },
        Ani1:{},
        Ani2:{},
        Ani3:{},
        Ani4:{},
        Ani5:{},
        Ani6:{},
        Ani7:{},
        Ani8:{},
        tipIsActive:0,
        NumIsActive:0,
        isActiveMessage:0,
        rockerIsActive:0,
        coffeeIsActive:0,
        maskIsActive:0,
        coffeeCupIsActive:0,
        cardShowIsActive:0,
        cardShowDetailIsActive:0,
        particleIsActive:0,
        lightIsActive:0,
        maskTipIsActive:0,
        ruleIsActive:0,
        historyIsActive:0,
        showTime:0,
        historyList:[],
        imgSrc:["",""],
        imgGif:[],
        imgFileList:[],
        aniBegin:0,
        cardSrc:"",
        card:[],
        category:["生椰拿铁","经典美式","经典拿铁","樱花拿铁","抹茶拿铁","摩卡"],
        nameRandom:[],
        swiperIsActive:0,
        TimeNum:0,
        durationTime:[],
    },
    onLoad(){
        var nameRandom=[]
        var durationTime=[0]
        for(var i=0;i<30;i++){
            nameRandom.push(wordRandom.getRandomName()+"抽到了"+this.data.category[Math.floor(Math.random()*6)])
        }
        for(var i=0;i<30;i++){
            durationTime.push(4000)
        }
        this.setData({
            nameRandom:nameRandom,
            durationTime:durationTime,
        })
        this.setData({
            //nameRandom:nameRandom,
            swiperIsActive:1,
        })
        var list=wx.getStorageSync("CardGetAnimation");
        console.log(list)
        this.setData({
            imgSrc:list.data,
        })
        console.log(this.data.imgSrc[0])
        this.getAnimationActive();
    },
    getTimeNum(){
        var userData=wx.getStorageSync("userData");
        this.setData({
            TimeNum: userData.data.time,
            NumIsActive:1,
        })
    },
    getAnimationActive(){
        this.setSkyAnimation();
        setTimeout(() =>{
            this.setCoffeeIpAnimation(834);
            setTimeout(() =>{
                this.setData({
                    tipIsActive:1
                })
                this.showTipAnimation()
                this.getTimeNum();
            },1000);
        },500);

        setTimeout(() =>{
            this.setTitleAnimation();
            setTimeout(() =>{
                this.setData({
                    isActiveMessage:1,
                })
            },500);
        },2500);
    },
    getImageOnload(){
        var fileList=new Array();
        for(var i=0;i<ImageSource.imageList[0].length;i++){
            var str=ImageSource.Base+ImageSource.page[0]+ImageSource.imageList[0][i]
            fileList.push(str)
        }
        var that=this;
        wx.cloud.getTempFileURL({
            fileList:fileList,
            success:res=>{
                var imgSrcList=new Array();
                const urls = res.fileList
                console.log('-------'+res.fileList[0].tempFileURL);
                that.setData({
                    imgFileList:res.fileList
                })
                const requests = urls.map(url => {
                    return new Promise(resolve => {
                        wx.downloadFile({
                            url: url.tempFileURL,
                             success (r) {
                                 resolve(r.tempFilePath);
                            },
                            fail:err=>{
                                console.log(err)
                            }
                        })
                    })
                })
                var imgSrcList=new Array()
                Promise.all(requests)
                    .then(objectUrls => {
                        imgSrcList.push(objectUrls)
                            }).then(() => {
                                    that.setData({
                                        imgSrc:imgSrcList,
                                    });
                                    this.getAnimationActive();
                            });
            },
            fail:err=>{
                console.log(err)
            }
        })
    },
    requestImg(item){
        var that = this;
        return new Promise((resolve,reject)=>{
            wx.request({
                url:item,
                header: {
                    'content-type': 'application/json' // 默认值
                },
                responseType: 'arraybuffer',
                success:res=>{
                    console.log(res)
                    let url ='data:image/png;base64,'+wx.arrayBufferToBase64(res.data)
                    resolve(url); // 返回给await
                }
            })
        });
    },
    //天空
    setSkyAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        var distance1=453.0/840.0*this.data.ScreenHeight
        var distance2=413.0/840.0*this.data.ScreenHeight
        console.log("distance1", distance1)
        animation.translateY(distance1).step({duration:453});
        animation.translateY(distance2).step({duration:47});
        this.setData({
            Ani1:animation.export(),
        })
    },
    //咖啡机出现
    setCoffeeIpAnimation(time){
        var distance=344/390*this.data.WindowWidth
        console.log("distance", distance)
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.translateX(-distance).opacity(1).step({duration:time});
        this.setData({
            Ani2:animation.export(),
        })
    },
    //咖啡机消失
    setCoffeeIpHideAnimation(){
        var distance=344/390*this.data.WindowWidth
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.translateX(-distance).scale(0.6).opacity(0).step({duration:1000});
        this.setData({
            Ani2:animation.export(),
        })
    },
    //副标题
    setTitleAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.opacity(1).step({duration:500});
        this.setData({
            Ani4:animation.export(),
        })
    },
    //提示信息
    showTipAnimation(){
        this.setData({
            tipIsActive:1,
        })
        console.log("show")
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.opacity(1).step({duration:500});
        this.setData({
            Ani3:animation.export(),
        })
    },
    setTipAnimation(){
        console.log("setTipAnimation")
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.rotate(15).step({duration:330});
        animation.rotate(-30).opacity(0).step({duration:667});
        this.setData({
            Ani3:animation,
        })
        setTimeout(() =>{
            this.setData({
                tipIsActive:0,
            })
        },1000);
    },
    setTipBackAnimation(){
        console.log("setTipBack")
        this.setData({
            tipIsActive:1,
        })
        var animation=wx.createAnimation({
            timingFunction:"linear"
        })
        animation.opacity(0).step({duration:1});
        this.setData({
            Ani3:animation.export(),
        })
    },
    //点击抽卡
    async cardGetItemTap(){
        if(this.data.TimeNum==0){
            wx.showToast({
                title:'次数用完',
                duration:1500
            })
            return ;
        }
        if(this.data.aniBegin==0){
            this.setData({
                aniBegin:1,
            })
        }else{return };
        this.setTipAnimation();
        await this.getOneCard();
        console.log("getItemTap");
        var that=this;
        setTimeout(() =>{
            console.log("here");
            wx.getImageInfo({
                src:that.data.imgSrc[0][2],
                success (res) {
                    console.log(res)
                    let temp='imgGif[0]'
                    console.log("iii")
                    that.setData({
                        [temp]:res.path,
                        rockerIsActive:1,
                    })
                }
            })
            setTimeout(() =>{
                wx.getImageInfo({
                    src:that.data.imgSrc[0][5],
                    success (res) {
                        console.log(res)
                        let temp='imgGif[1]'
                        that.setData({
                            [temp]:res.path,
                            coffeeIsActive:1,
                        })
                    }
                })
            },600);
            that.cardGetAnimation();
        },0);
    },
    //抽卡动画
    cardGetAnimation(){
        setTimeout(() =>{
            this.setCoffeeIpHideAnimation();
            this.setData({
                maskIsActive:1,
            })
            var that=this;
            setTimeout(() =>{
                this.getMaskAnimation();
                wx.getImageInfo({
                    src:that.data.imgSrc[0][0],
                    success (res) {
                        console.log(res)
                        let temp1='imgGif[2]'
                        wx.getImageInfo({
                            src:that.data.imgSrc[0][1],
                            success (r) {
                                console.log(res)
                                let temp2='imgGif[3]'
                                that.setData({
                                    [temp1]:res.path,
                                    [temp2]:r.path,
                                    coffeeCupIsActive:1,
                                    cardShowIsActive:1,
                                })
                            }
                        })
                    }
                })
                setTimeout(() =>{
                    this.getCardAnimation();
                    setTimeout(() =>{
                        wx.getImageInfo({
                            src:that.data.imgSrc[0][6],
                            success (res) {
                                console.log(res)
                                let temp='imgGif[4]'
                                that.setData({
                                    [temp]:res.path,
                                    particleIsActive:1
                                })
                            }
                        })
                        setTimeout(() =>{
                            that.setData({
                                lightIsActive:1
                            })
                            setTimeout(() =>{
                                that.getLightAnimation()
                                that.setData({
                                    particleIsActive:0,
                                    cardShowDetailIsActive:1
                                })
                                setTimeout(() =>{
                                    that.setWordAnimation();
                                    that.setData({
                                        coffeeCupIsActive:0
                                    })
                                },200)
                            },500)
                        },500)
                    },500);
                },500);
            },500);
        },2000);
    },
    getRuleItemTap(e){
        this.setData({
            ruleIsActive:1,
            maskTipIsActive:1,
        })
    },
    getHistoryItemTap(e){
        var userCard=wx.getStorageSync("userCards");
        console.log(userCard.data[0])
        var list=[]
        list=userCard.data.flat(Infinity)
        list.sort(function(a,b){
            if(a.date<b.date||(a.date==b.date&&a.id<b.id))return 1
            else return -1
        })
        var nowTime=new Date(app.globalData.nowTime.substring(0,10))
        let date=new Date(nowTime-7 * (3600 * 24 * 1000)).toISOString().substring(0,10)
        var count=0;
        list.forEach(item=>{
            if(item.date>date){
                count++;
            }
        });
        list.length=count;
        this.setData({
            historyList:list,
            historyIsActive:1,
            maskTipIsActive:1,
        })
    },
    closeTipShowItemTap(){
        this.setData({
            ruleIsActive:0,
            historyIsActive:0,
            maskTipIsActive:0,
        })
    },
    //蒙版
    getMaskAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.opacity(0.7).step({duration:496})
        this.setData({
            Ani5:animation.export(),
        })
    },
    //卡片动画
    getCardAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.translateY(0).scale(1).rotate(0).step({duration:1000})
        this.setData({
            Ani6:animation.export(),
        })
    },
    getCardBackAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        var distance=this.data.ScreenHeight*719/844;
        console.log(distance)
        animation.translateY(distance).scale(0.77).rotate(210).step({duration:0})
        this.setData({
            Ani6:animation.export(),
        })
    },
    //字体动画
    setWordAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.opacity(1).step({duration:1000});
        this.setData({
            Ani8:animation.export(),
        })
    },
    setWordBackAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"ease"
        })
        animation.opacity(0).step({duration:0});
        this.setData({
            Ani8:animation.export(),
        })
    },
    //光线动画
    getLightAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"linear"
        })
        animation.rotate(-9).opacity(1).step({duration:500})
        animation.rotate(-81).opacity(1).step({duration:4000})
        animation.rotate(-90).opacity(0).step({duration:500})
        this.setData({
            Ani7:animation.export(),
        })
    },
    getLightBackAnimation(){
        var animation=wx.createAnimation({
            timingFunction:"linear"
        })
        animation.rotate(-0).step({duration:0})
        this.setData({
            Ani7:animation.export(),
            lightIsActive:0,
        })
    },
    preventTouchMove(){

    },
    closeCardItemTap(e){
        console.log(e);
        this.getLightBackAnimation()
        this.getCardBackAnimation()
        this.setWordBackAnimation()
        var that=this;
        setTimeout(() =>{
            that.setData({
                rockerIsActive:0,
                coffeeIsActive:0,
                maskIsActive:0,
                coffeeCupIsActive:0,
                cardShowIsActive:0,
                cardShowDetailIsActive:0,
                particleIsActive:0,
                aniBegin:0,
            })
            setTimeout(() =>{
                that.setTipBackAnimation()
                setTimeout(() =>{
                    that.setCoffeeIpAnimation(100)
                    setTimeout(() =>{
                        that.showTipAnimation()
                    })
                },200)
            },200)
        },100)
        console.log(this.data.showTime)
    },
    //获取一张卡片
    getOneCard(){
        var that = this;
        return new Promise(resolve =>{
            that.setData({
                TimeNum: this.data.TimeNum-1,
            })
            let params={
                url:'/getCard',
                method: 'GET',
                data: {
                    openId:app.globalData.openId,
                },
            }
            request(params).then(res=>{
                const data=JSON.parse(crypto.AES_DE(res.data))
                console.log(data)
                var src=ImageSource.Base+"/icon/roleCard/"+data.image;
                wx.cloud.getTempFileURL({
                    fileList:[src],
                    success:r=>{
                        that.setData({
                            cardSrc:r.fileList[0].tempFileURL,
                            card:data
                        })
                        dataGet.getUserCardData()
                        resolve()
                    }
                })
            })
        })
    },
    getOrderItemTap(){
        wx.showToast({
            title: '您喝了一杯',
            icon:"none",
            duration: 1500,
        })
        this.closeCardItemTap();
    }
})